package com.ruoyi.common.core.redis;

import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录错误次数
 */
@Component
public class UserPasswordRetryLimitService {
    private static String overSessionName="password_retry";
    @Autowired
    private RedisCache redisCache;

    /**
     * 是否超过最大次数
     * @param userId
     * @return
     */
    public boolean isOverload(String userId){
        LoginErrorEntity entity=redisCache.getCacheMapValue(overSessionName,userId);
        if(entity!=null){
            if(entity.getLastTime()+ RuoYiConfig.getLockTime()*60*1000<System.currentTimeMillis()){
                return false;
            }else if(entity.getCount()>=RuoYiConfig.getMaxRetryCount()){
                return true;
            }
        }
        return false;
    }

    public int error(String userId){
        LoginErrorEntity entity=redisCache.getCacheMapValue(overSessionName,userId);
        if(entity==null){
            entity=new LoginErrorEntity();
            entity.setCount(1);
        }else if(entity.getLastTime()+ RuoYiConfig.getLockTime()*60*1000<System.currentTimeMillis()){
            entity.setCount(1);
        }else{
            entity.setCount(entity.getCount()+1);
        }
        entity.setLastTime(System.currentTimeMillis());
        redisCache.setCacheMapValue(overSessionName,userId,entity);
        return entity.getCount();
    }

    public void success(String userId){
        redisCache.delCacheMapValue(overSessionName,userId);
    }
}

class LoginErrorEntity{
    private int count;
    private long lastTime;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public long getLastTime() {
        return lastTime;
    }

    public void setLastTime(long lastTime) {
        this.lastTime = lastTime;
    }
}
